package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Author: Zheng
 * Date:   2024/2/29  10:03
 * Package：com.sky.task
 * Description：
 * Version：1.0
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * @description： 处理支付超时订单
     * @date：2024/2/29  10:09
     * @return：
     **/
    @Scheduled(cron = "0 * * * * ?") //每分钟触发
    public void processTimeoutOrder(){
        log.info("处理支付超时订单：{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().minusMinutes(15);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.PENDING_PAYMENT,time);
        if (ordersList == null && ordersList.isEmpty()){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        ordersList.forEach(orders -> {
           orders.setStatus(Orders.CANCELLED);
           orders.setCancelReason("支付超时，自动取消！");
           orders.setCancelTime(LocalDateTime.now());
           ordersMapper.update(orders);
        });
    }

    /**
     * @description： 处理派送中订单
     * @date：2024/2/29  10:10
     * @return：
     **/
    @Scheduled(cron = "0 0 2 * * ?")
    public void processDeliveryOrder(){
        log.info("处理派送中订单：{}",LocalDateTime.now());

        LocalDateTime time = LocalDateTime.now().minusHours(2);
        List<Orders> ordersList = ordersMapper.selectByStatusAndOrderTime(Orders.DELIVERY_IN_PROGRESS,time);
        if (ordersList == null && ordersList.isEmpty()){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        ordersList.forEach(orders -> {
            orders.setStatus(Orders.COMPLETED);
            orders.setDeliveryTime(LocalDateTime.now());
            ordersMapper.update(orders);
        });
    }
}
